<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
require_once 'Log.php';
require_once 'MainController.php';

class Home extends MainController {

    private $logger;

    public function __construct() {
        parent::__construct();
        $this->logger = new TS_Log(get_class());
    }

    public function index() {
        $this->load->library('form_validation');
        $this->check_isvalidated();
        $this->load->view("HomeView");
    }

    private function generateRandomString($length) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }

    public function signup() {
        $this->logger->log('info', '------------ Signup');
        $this->load->library('form_validation');
        $username = $this->input->post("signup-username");
        $email = $this->input->post("signup-email");
        $password = $this->input->post("signup-password");
        $signup_button = $this->input->post("signup_button");

        $this->logger->log('info', '------- input --------');
        $this->logger->log('info', 'username : ' . $username);
        $this->logger->log('info', 'email : ' . $email);
        $this->logger->log('info', 'password : ' . $password);
        $this->logger->log('info', '------- output -------');

        if (isset($signup_button)) {
            $this->form_validation->set_rules('signup-username', 'Username', 'trim|required|is_unique[user.username]');
            $this->form_validation->set_rules('signup-password', 'Password', 'trim|required||min_length[6]|callback_password_check');
            $this->form_validation->set_rules('signup-email', 'Email', 'trim|required|valid_email|is_unique[user.email]');

            $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
            if ($this->form_validation->run() == TRUE) {
                $this->load->model('UserModel');
                $this->UserModel->insertBySignup($username, $email, $password);
                $this->loadView($this, 'HomeView', null);
            } else {
                $this->loadView($this, 'HomeView', null);
            }
        }
    }

    public function signin() {
        $this->logger->log('info', '------------ Signin');
        $this->load->library('form_validation');
        $username = $this->input->post("signin-username");
        $password = $this->input->post("signin-password");
        $signin_button = $this->input->post("signin-button");
        $signin_captcha = $this->input->post("signin-captcha");

        $this->logger->log('info', '------- input --------');
        $this->logger->log('info', 'username : ' . $username);
        $this->logger->log('info', 'password : ' . $password);
        $this->logger->log('info', '------- output -------');

        if (isset($signin_button)) {
            $countSignin = $this->session->userdata('count_signin');
            if ($countSignin >= 3) {
                $this->form_validation->set_rules('signin-captcha', 'Captcha', 'trim|required|callback_checkCaptchaWord');
            }
            $this->form_validation->set_rules('signin-username', 'Username', 'trim|required');
            $this->form_validation->set_rules('signin-password', 'Password', 'trim|required');

            $this->form_validation->set_error_delimiters('<div class="error">', '</div>');

            if ($this->form_validation->run() == TRUE) {
                $this->load->model('UserModel');
                $result = $this->UserModel->getNumRowsByUsernameAndPassword($username, $password);
                $this->logger->log("info", "--------------- num rows : " . $result->num_rows());
                if (isset($result) && $result->num_rows() == 1) {
                    $data = $result->row();
                    $this->logger->log("info", "--------------- username : " . $data->username);
                    $this->logger->log("info", "--------------- email : " . $data->email);
                    $session = array(
                        'user_id' => $this->encrypt->encode($data->id),
                        'username' => $this->encrypt->encode($data->username),
                        'email' => $this->encrypt->encode($data->email),
                        'validate' => TRUE
                    );
                    $this->session->set_userdata($session);
                    $this->session->unset_userdata('count_signin');
                    $this->session->unset_userdata('captcha-word');
                    redirect();
                } else {
                    $data["signin_error"] = "Invalid username or password please try agian.";

                    if ($countSignin) {
                        ++$countSignin;
                        $this->session->set_userdata('count_signin', $countSignin);
                    } else {
                        $this->session->set_userdata('count_signin', 1);
                    }

                    if ($countSignin >= 3) {
                        $captcha = $this->initialCaptcha();
                        $data['image'] = $captcha['image'];
                    }

                    $this->loadView($this, 'HomeView', $data);
                }
            } else {
                if ($countSignin >= 3) {
                    $captcha = $this->initialCaptcha();
                    $this->loadView($this, 'HomeView', $captcha);
                }

                $this->loadView($this, 'HomeView', null);
            }
        }
    }

    public function checkCaptchaWord($str) {
        $word = $this->session->userdata('captcha-word');
        echo $word;
        if ($word != $str) {
            $this->form_validation->set_message('checkCaptchaWord', 'Invalid %s code.');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    private function initialCaptcha() {
        $vals = array(
            'img_path' => './asset/captcha/',
            'img_url' => base_url('asset/captcha') . '/',
            'font_path' => './asset/fonts/Kingthings-Christmas-2.2.ttf',
            'img_width' => '350',
            'img_height' => 80,
            'expiration' => 7200
        );

        /* Generate the captcha */
        $captcha = create_captcha($vals);

        $data = array(
            'captcha_time' => $captcha['time'],
            'ip_address' => $this->input->ip_address(),
            'word' => $captcha['word']
        );

        $query = $this->db->insert_string('captcha', $data);
        $this->db->query($query);

        $this->session->set_userdata('captcha-word', $captcha['word']);

        return $captcha;
    }

    private function check_isvalidated() {
        $validate = $this->session->userdata('validate');
        $user_id = $this->session->userdata('user_id');
        if (isset($validate) && isset($user_id)) {
            if ($validate) {
                $this->logger->log('info', '---------------- validate : ' . $validate);
                $this->logger->log('info', '---------------- user_id : ' . $this->encrypt->decode($user_id));
                redirect(base_url('Profile'));
            }
        }
    }

    public function do_logout() {
        $this->session->sess_destroy();
        redirect('Home');
    }

    public function password_check($str) {
        if (preg_match('#[0-9]#', $str) && preg_match('#[a-zA-Z]#', $str)) {
            return TRUE;
        }
        $this->form_validation->set_message('password_check', 'The %s must be 0-9 and a-z.');
        return FALSE;
    }

}
